package com.naizhuai.ui.mianbusiness.setting;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.naizhuai.Model.db.user.PersonUserBean;
import com.naizhuai.R;
import com.naizhuai.network.exception.ApiException;
import com.naizhuai.ui.BaseActivity;
import com.naizhuai.ui.adapter.ChosenChargeJoinAdapterHolder;
import com.naizhuai.ui.adapter.management.UserAbilityAdapter;
import com.naizhuai.ui.components.CircleImageView;
import com.naizhuai.ui.components.LabelsView;
import com.naizhuai.ui.components.RadarData;
import com.naizhuai.ui.components.RadarView;
import com.naizhuai.ui.components.SingleLabelsView;
import com.naizhuai.ui.entity.ChargeCheckItemBean;
import com.naizhuai.ui.entity.VirtualChosenBean;
import com.naizhuai.ui.entity.management.DepartmentBean;
import com.naizhuai.ui.entity.setting.UserAbilityLabels;
import com.naizhuai.ui.entity.setting.UserRadarLabels;
import com.naizhuai.ui.management.CompanyAddPartActivity;
import com.naizhuai.ui.mianbusiness.presenter.PublicDataApiStoreIml;
import com.naizhuai.ui.mianbusiness.setting.presenter.UserPersonalApiStoreIml;
import com.naizhuai.ui.mianbusiness.target.TargetCreateActivity;
import com.naizhuai.util.ConstantsState;
import com.naizhuai.util.DialogUtils;
import com.naizhuai.util.ErrorViewCreateUtils;
import com.naizhuai.util.ImageUtils;
import com.naizhuai.util.IntentUtils;
import com.naizhuai.util.ListUtils;
import com.naizhuai.util.NaizhuAILog;
import com.naizhuai.util.RxBus;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Observer;
import rx.Subscription;

/**
 * 选择人员以及详情的列表界面
 */
public class UserListChosenActivity extends BaseActivity implements ChosenChargeJoinAdapterHolder.OnItemClickListener, View.OnClickListener, TextWatcher {
    private static final String TAG = "UserListChosenActivity";

    public static final String JOIN_PERSON_KEY = "join_person_key";
    public static final String JOIN_DEPARTMENT_KEY = "join_department_key";

    public static final String ENTER_CHOSEN_TYPE_KEY = "chosen_type_key";
    public static final int ENTER_CHOSEN_TYPE_LIMITED = 1111;
    public static final int ENTER_CHOSEN_TYPE_UNLIMITED = 1112;


    @BindView(R.id.chose_user_list)
    RecyclerView chosenList;
    @BindView(R.id.bottom_layout)
    RelativeLayout bottomLayout;
    private ChosenChargeJoinAdapterHolder joinAdapter;
    private List<ChargeCheckItemBean<VirtualChosenBean>> virtualBeanList;

    @BindView(R.id.muti_chosen)
    TextView mutiChose;
    @BindView(R.id.single_chose)
    LinearLayout singleChose;
    @BindView(R.id.sure_chosen)
    TextView sureBtn;
    @BindView(R.id.chose_thumb)
    CircleImageView choseThumb;
    @BindView(R.id.chosen_name)
    TextView choseName;
    @BindView(R.id.search_member)
    EditText searchMember;

    @BindView(R.id.search_layout)
    RelativeLayout searchLayout;
    @BindView(R.id.team_txt)
    TextView teamTxt;

    private VirtualChosenBean choseBean;

    private int enterType;
    private int filedType;
    private int limitType;
    private String serverId;
    private String chosePersonStr;
    private String choseDepartStr;

    private Set<String> checkedIdSet;
    private Map<String, VirtualChosenBean> checkBean;

    private Observer<List<VirtualChosenBean>> observer;

    private Subscription chosenSub;

    @BindView(R.id.error_content)
    RelativeLayout errorLayout;
    @BindView(R.id.list_content)
    NestedScrollView scrollView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initBaseData();
        initBaseView();
        initObserver();
        requestData("");
    }


    private void initBaseData() {
        virtualBeanList = new ArrayList<>();
        checkedIdSet = new HashSet<>();
        checkBean = new HashMap<>();
        Bundle bundle = getIntent().getExtras();
        chosePersonStr = getText(R.string.has_chosen_number).toString();
        choseDepartStr = getText(R.string.has_chosen_department).toString();
        if (bundle != null) {
            enterType = bundle.getInt(ChosenChargeJoinAdapterHolder.ENTER_TYPE_KEY, ChosenChargeJoinAdapterHolder.TYPE_CHOSEN_PERSON);
            filedType = bundle.getInt(ConstantsState.CHOSEN_USER_TYPE_KEY, ConstantsState.CHOSEN_TARGET_USER_TYPE);
            limitType = bundle.getInt(ENTER_CHOSEN_TYPE_KEY, ENTER_CHOSEN_TYPE_UNLIMITED);
            serverId = bundle.getString(ConstantsState.SERVER_ID_KEY, "");
        }

    }

    private void initBaseView() {
        sureBtn.setEnabled(false);
        errorLayout.setVisibility(View.VISIBLE);
        scrollView.setVisibility(View.INVISIBLE);
        bottomLayout.setVisibility(View.INVISIBLE);
        errorLayout.removeAllViews();
        errorLayout.addView(ErrorViewCreateUtils.createLoadingView(this));
        if (enterType == ChosenChargeJoinAdapterHolder.TYPE_CHOSEN_MANAGE || enterType == ChosenChargeJoinAdapterHolder.TYPE_CHOSEN_TEAM_MAIN_MANAGER) {
            singleChose.setVisibility(View.VISIBLE);
            mutiChose.setVisibility(View.GONE);
        } else {
            singleChose.setVisibility(View.GONE);
            mutiChose.setVisibility(View.VISIBLE);
        }
        searchMember.addTextChangedListener(this);
        initRecyclerView();
    }

    private void initRecyclerView() {
        joinAdapter = new ChosenChargeJoinAdapterHolder(this, virtualBeanList, enterType);
        chosenList.setNestedScrollingEnabled(false);
        chosenList.setHasFixedSize(true);
        chosenList.setLayoutManager(new LinearLayoutManager(this));
        chosenList.setItemAnimator(new DefaultItemAnimator());
        chosenList.setAdapter(joinAdapter);
        joinAdapter.setOnItemClickListener(this);
    }


    private void initErrorLayout() {
        errorLayout.setVisibility(View.VISIBLE);
        errorLayout.removeAllViews();
        errorLayout.addView(ErrorViewCreateUtils.createLoadingView(this));
    }


    private void initObserver() {
        observer = new Observer<List<VirtualChosenBean>>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                NaizhuAILog.e("onError=e=" + e.getMessage());
                ApiException.showException(e, getActivityContext());
                errorLayout.setVisibility(View.VISIBLE);
                scrollView.setVisibility(View.INVISIBLE);
                bottomLayout.setVisibility(View.INVISIBLE);
                errorLayout.removeAllViews();
                errorLayout.addView(ErrorViewCreateUtils.createNoNetworkView(getActivityContext(), v -> {
                    initErrorLayout();
                    requestData(searchMember.getText().toString());
                }));
            }

            @Override
            public void onNext(List<VirtualChosenBean> virtualChosenBeans) {
                virtualBeanList.clear();
                virtualBeanList = ListUtils.AddChangeList(virtualBeanList, virtualChosenBeans, checkedIdSet);
                if (virtualBeanList.size() > 0) {
                    joinAdapter.notifyDataSetChanged();
                    errorLayout.setVisibility(View.INVISIBLE);
                    scrollView.setVisibility(View.VISIBLE);
                    bottomLayout.setVisibility(View.VISIBLE);
                } else {
                    errorLayout.setVisibility(View.VISIBLE);
                    scrollView.setVisibility(View.INVISIBLE);
                    bottomLayout.setVisibility(View.INVISIBLE);
                    errorLayout.removeAllViews();
                    errorLayout.addView(ErrorViewCreateUtils.createNoSearchView(getActivityContext()));
                }
            }
        };
    }

    private void requestData(String str) {
        if (enterType == ChosenChargeJoinAdapterHolder.TYPE_CHOSEN_DEPARTMENT) {
            chosenSub = PublicDataApiStoreIml.getInstance().getChosenGroup(ConstantsState.CHOSEN_TARGET_USER_TYPE, "").subscribe(observer);
            searchLayout.setVisibility(View.GONE);
            teamTxt.setVisibility(View.VISIBLE);
        } else {
            searchLayout.setVisibility(View.VISIBLE);
            teamTxt.setVisibility(View.GONE);
            filterExeEnterType(str);
        }
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_filed_chosen_list;
    }


    @Override
    public void onItemClick(View view, int position, int clickType) {
        switch (clickType) {
            case ChosenChargeJoinAdapterHolder.TYPE_CLICK_CHOSEN:
                if (limitType == ENTER_CHOSEN_TYPE_UNLIMITED)
                    chosenClickType(position);
                else {
                    if (!virtualBeanList.get(position).isCheck() && DialogUtils.userFatigueSuitable(virtualBeanList.get(position).getPersonUser().getShowLabels().get(1).getValue(), this)) {
                        DialogUtils.showSureDialog(this, getString(R.string.tired_too_large), new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                chosenClickType(position);
                            }
                        });
                    } else {
                        chosenClickType(position);
                    }
                }
                break;
            case ChosenChargeJoinAdapterHolder.TYPE_CLICK_DETAILS:
                IntentUtils.startActivityWithString(PersonUserBean.USER_ID_KEY, virtualBeanList.get(position).getPersonUser().getSelectedId(), this, PersonRadarActivity.class);
                break;
        }
    }

    private void chosenClickType(int position) {
        for (int index = 0; index < virtualBeanList.size(); index++) {
            ChargeCheckItemBean<VirtualChosenBean> clickBean = virtualBeanList.get(index);
            if (enterType == ChosenChargeJoinAdapterHolder.TYPE_CHOSEN_MANAGE || enterType == ChosenChargeJoinAdapterHolder.TYPE_CHOSEN_TEAM_MAIN_MANAGER) {
                if (position == index) {
                    if (clickBean.isCheck()) {
                        choseBean = null;
                        clickBean.setCheck(!clickBean.isCheck());
                        choseName.setText("");
                        choseThumb.setVisibility(View.GONE);
                    } else {
                        choseBean = clickBean.getPersonUser();
                        clickBean.setCheck(!clickBean.isCheck());
                        choseName.setText(clickBean.getPersonUser().getName());
                        choseThumb.setVisibility(View.VISIBLE);
                        ImageUtils.glideThumbViewByUrl(this, choseThumb, clickBean.getPersonUser().getUserThumb());
                    }
                } else {
                    if (clickBean.isCheck())
                        clickBean.setCheck(false);
                }
            } else {
                String selectedId = clickBean.getPersonUser().getSelectedId();
                if (position == index) {
                    if (clickBean.isCheck()) {
                        clickBean.setCheck(false);
                        checkedIdSet.remove(selectedId);
                        checkBean.remove(selectedId);
                    } else {
                        clickBean.setCheck(true);
                        checkedIdSet.add(selectedId);
                        checkBean.put(selectedId, clickBean.getPersonUser());
                    }
                }
            }
        }
        if (mutiChose.getVisibility() == View.VISIBLE) {
            if (enterType == ChosenChargeJoinAdapterHolder.TYPE_CHOSEN_DEPARTMENT)
                mutiChose.setText(String.format(choseDepartStr, checkBean.size()));
            else if (enterType != ChosenChargeJoinAdapterHolder.TYPE_CHOSEN_MANAGE && enterType != ChosenChargeJoinAdapterHolder.TYPE_CHOSEN_TEAM_MAIN_MANAGER)
                mutiChose.setText(String.format(chosePersonStr, checkBean.size()));
        }

        joinAdapter.notifyDataSetChanged();
        if (checkBean.size() == 0 && choseBean == null)
            sureBtn.setEnabled(false);
        else
            sureBtn.setEnabled(true);
    }

    @OnClick({R.id.sure_chosen, R.id.base_back_icon})
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.sure_chosen:
                Intent data = new Intent();
                if (enterType == ChosenChargeJoinAdapterHolder.TYPE_CHOSEN_DEPARTMENT) {
                    List<DepartmentBean> department = new ArrayList<>();
                    if (virtualBeanList.size() > 0) {
                        for (ChargeCheckItemBean<VirtualChosenBean> bean : virtualBeanList) {
                            if (bean.isCheck()) {
                                VirtualChosenBean chose = bean.getPersonUser();
                                DepartmentBean depart = new DepartmentBean();
                                depart.setDepartmentId(chose.getSelectedId());
                                depart.setDepartmentName(chose.getName());
                                department.add(depart);
                            }
                        }
                    } else {
                        shortToast(getString(R.string.has_no_choise));
                        return;
                    }
                    Bundle bundle = new Bundle();
                    bundle.putSerializable(JOIN_DEPARTMENT_KEY, (Serializable) department);
                    data.putExtras(bundle);
                    setResult(TargetCreateActivity.CHOSE_JOIN_DEPARTMENT, data);
                } else {
                    if (enterType != ChosenChargeJoinAdapterHolder.TYPE_CHOSEN_MANAGE && enterType != ChosenChargeJoinAdapterHolder.TYPE_CHOSEN_TEAM_MAIN_MANAGER) {
                        List<PersonUserBean> userList = new ArrayList<>();
                        if (virtualBeanList.size() > 0) {
                            for (VirtualChosenBean chose : checkBean.values()) {
                                PersonUserBean user = new PersonUserBean();
                                user.setUid(chose.getSelectedId());
                                user.setNickName(chose.getName());
                                user.setUserLogoUrl(chose.getUserThumb());
                                userList.add(user);
                            }
                        } else {
                            shortToast(getString(R.string.has_no_choise));
                            return;
                        }
//                        if (virtualBeanList.size() > 0) {
//                            for (ChargeCheckItemBean<VirtualChosenBean> bean : virtualBeanList) {
//                                if (bean.isCheck()) {
//                                    VirtualChosenBean chose = bean.getPersonUser();
//                                    PersonUserBean user = new PersonUserBean();
//                                    user.setUid(chose.getSelectedId());
//                                    user.setNickName(chose.getName());
//                                    userList.add(user);
//                                }
//                            }
//                        }
                        Bundle bundle = new Bundle();
                        bundle.putSerializable(JOIN_PERSON_KEY, (Serializable) userList);
                        data.putExtras(bundle);
                        switch (enterType) {
                            case ChosenChargeJoinAdapterHolder.TYPE_CHOSEN_PERSON:
                                setResult(TargetCreateActivity.CHOSE_JOIN_PEOPLE, data);
                                break;
                            case ChosenChargeJoinAdapterHolder.TYPE_ADD_PERSON_MANAGE:
                                setResult(CompanyAddPartActivity.ADD_MANAGERS_CODE, data);
                                break;

                            case ChosenChargeJoinAdapterHolder.TYPE_ADD_PERSON:
                                setResult(CompanyAddPartActivity.ADD_MEMBER_CODE, data);
                                break;

                            case ChosenChargeJoinAdapterHolder.TYPE_THANKS_PERSON:
                                setResult(ThankSettingPagerActivity.CHOSEN_THANK_USERS, data);
                                break;

                            case ChosenChargeJoinAdapterHolder.TYPE_CHOSEN_TEAM_MAIN_MANAGER:
                                setResult(CompanyAddPartActivity.ADD_MEMBER_MAIN, data);
                                break;
                        }
                    } else {
                        if (choseBean == null) {
                            shortToast(getString(R.string.has_no_choise));
                            return;
                        }
                        PersonUserBean user = new PersonUserBean();
                        user.setUid(choseBean.getSelectedId());
                        user.setNickName(choseBean.getName());
                        user.setUserLogoUrl(choseBean.getUserThumb());
                        Bundle bundle = new Bundle();
                        bundle.putSerializable(TargetCreateActivity.CHARGE_KEY, user);
                        data.putExtras(bundle);
                        setResult(TargetCreateActivity.CHOSE_CHARGE, data);
                    }
                }
                finish();
                break;
            case R.id.base_back_icon:
                onBackPressed();
                break;
        }
    }

    private void filterExeEnterType(String str) {
        switch (enterType) {
            case ChosenChargeJoinAdapterHolder.TYPE_CHOSEN_PERSON:
                chosenSub = PublicDataApiStoreIml.getInstance().getChosenPeople(filedType, serverId, str).subscribe(observer);
                break;
            case ChosenChargeJoinAdapterHolder.TYPE_CHOSEN_MANAGE:
//                if (!TextUtils.isEmpty(serverId)) {
                chosenSub = PublicDataApiStoreIml.getInstance().getChosenManage(filedType, serverId, str).subscribe(observer);
//                } else {
//                    PublicDataApiStoreIml.getInstance().getThankPeople(str).subscribe(observer);
//                }
                break;
            case ChosenChargeJoinAdapterHolder.TYPE_ADD_PERSON:
                chosenSub = PublicDataApiStoreIml.getInstance().getAddPeople(str).subscribe(observer);
                break;
            case ChosenChargeJoinAdapterHolder.TYPE_ADD_PERSON_MANAGE:
                chosenSub = PublicDataApiStoreIml.getInstance().getAddPeople(str).subscribe(observer);
                break;
            case ChosenChargeJoinAdapterHolder.TYPE_THANKS_PERSON:
                chosenSub = PublicDataApiStoreIml.getInstance().getThankPeople(str).subscribe(observer);
                break;
            case ChosenChargeJoinAdapterHolder.TYPE_CHOSEN_TEAM_MAIN_MANAGER:
                chosenSub = PublicDataApiStoreIml.getInstance().getAddPeople(str).subscribe(observer);
                break;
        }
    }

    @Override
    public void onBackPressedWithoutDialog() {
        if (chosenSub != null && !chosenSub.isUnsubscribed())
            DialogUtils.showSureDialog(this, getString(R.string.cancel_submit_request), new View.OnClickListener() {
                @Override
                public void onClick(View dialog) {
                    chosenSub.unsubscribe();
                    errorLayout.setVisibility(View.VISIBLE);
                    errorLayout.removeAllViews();
                    errorLayout.addView(ErrorViewCreateUtils.createNoNetworkView(getActivityContext(), v -> {
                        initErrorLayout();
                        requestData(searchMember.getText().toString());
                    }));
                }
            });
        else
            super.onBackPressedWithoutDialog();
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    @Override
    public void onTextChanged(CharSequence str, int start, int before, int count) {
        //文字改变时候的回调
        filterExeEnterType(str.toString());

    }

    @Override
    public void afterTextChanged(Editable s) {

    }
}
